import requests 
import json
import datetime

with open('weblog.txt', 'r') as fp:
    weblog = []
    while True:
        text = fp.readline ()
        if not text:
            break
        one_data = {}
        lst = text.split()
        one_data['ip'] = lst[0]
        time_format = datetime.datetime.strptime(lst[3].replace('[',''), '%d/%b/%Y:%H:%M:%S')
        one_data['datetime'] = str(time_format)
        one_data['wide'] = lst[9]
        weblog.append(one_data)
   
baseUrl = 'https://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip='
fp = open('ip_msg.txt', 'x', encoding='utf-8')
for i in weblog:
    url = baseUrl + i['ip']
    response = requests.get(url)
    json_date = json.loads(response.text)
    date = json_date['data']
    i['region'] = date.get('region', '无')
    i['isp'] = date.get('isp', '无')
    # print(i)
    fp.write(f"{i['datetime']},{i['region']},{i['isp']},{i['wide']}\n")
fp.close()

